package com.drd.dt.util;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.Charset;

/**
 * @author jianbo_chen
 */
public class SecurityUtil {

	public final static Charset UTF8 = Charset.forName("UTF-8");

	public static class MacHashFunction {
		public final Mac mac;

		public MacHashFunction(Mac mac) {
			this.mac = mac;
		}

		public MacHashFunction hash(String input) {
			this.mac.update(input.getBytes(UTF8));
			return this;
		}

		public MacHashFunction hash(byte[] input) {
			this.mac.update(input);
			return this;
		}

		public String result() {
			byte[] sha1Bytes = mac.doFinal();
			return DatatypeConverter.printBase64Binary(sha1Bytes);
		}
	}

	public static MacHashFunction hmacSha1(String key) {
		try {
			SecretKey secretKey = new SecretKeySpec(key.getBytes(UTF8), "HmacSHA1");
			Mac mac = Mac.getInstance(secretKey.getAlgorithm());
			mac.init(secretKey);
			return new MacHashFunction(mac);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String hmacSha1(String key, String data) {
		try {
			SecretKey secretKey = new SecretKeySpec(key.getBytes(UTF8), "HmacSHA1");
			Mac mac = Mac.getInstance(secretKey.getAlgorithm());
			mac.init(secretKey);
			byte[] sha1Bytes = mac.doFinal(data.getBytes(UTF8));
			return DatatypeConverter.printBase64Binary(sha1Bytes);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}